<template>
  <!-- 搜索栏+新增按钮 -->
  <el-form :model="searchFormData" label-width="50px">
    <el-row>
      <el-col :span="4">
        <el-form-item label="昵称:" prop="nickName">
          <el-input
            placeholder="请输入昵称"
            v-model="searchFormData.nickNameFuzzy"
            clearable
            @keyup.enter="getDataList"
            @clear="getDataList"
          />
        </el-form-item>
      </el-col>
      <el-col :span="4">
        <el-form-item label="手机号:" prop="phone" label-width="80px">
          <el-input
            placeholder="请输入手机号"
            v-model="searchFormData.phoneFuzzy"
            clearable
            @keyup.enter="getDataList"
            @clear="getDataList"
          />
        </el-form-item>
      </el-col>
      <el-col :span="5" :style="{ 'padding-left': '10px' }">
        <el-button type="primary" @click="getDataList">搜索</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-button type="primary" @click="openUserVisible('add')">新增用户</el-button>
      </el-col>
    </el-row>
  </el-form>
  <!-- 数据表格 -->
  <el-table
    class="dataTable"
    :data="tableData.list"
    stripe
    :border="true"
    style="width: 100%"
  >
    <el-table-column label="#" width="36" type="index" />
    <el-table-column prop="avatar" label="头像" width="100">
      <template #default="scope">
        <div style="display: flex; align-items: center">
          <el-image
            style="width: 80px; height: 80px"
            fit="fill"
            :src="proxy.imageUrl + scope.row.avatar"
          />
        </div>
      </template>
    </el-table-column>
    <el-table-column label="用户信息" min-width="200">
      <template #default="scope">
        <div class="blogInfo">
          <span>昵称:{{ scope.row.nickName }}</span>
          <span>手机号:{{ scope.row.phone }}</span>
          <span>职业:{{ scope.row.profession }}</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="editorTypeName" label="编辑器" width="100" />
    <el-table-column prop="roleTypeName" label="角色" width="80" />
    <el-table-column prop="status" label="状态" width="80">
      <template #default="{ row }">
        <el-switch
          :model-value="row.status == 0 ? false : true"
          inline-prompt
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          active-text="启用"
          inactive-text="禁用"
          :loading="loading"
          @click="beforeChange(row)"
        />
      </template>
    </el-table-column>
    <el-table-column label="时间" width="253">
      <template #default="scope">
        <div class="timeInfo">
          <span>创建时间:{{ scope.row.createTime }}</span>
          <span>最后登录时间:{{ scope.row.lastLoginTime }}</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="240">
      <template #default="scope">
        <el-button
          type="primary"
          plain
          @click="openUserVisible('edit', scope.row)"
        >
          <Edit style="width: 1em; height: 1em" />
        </el-button>
        <el-divider direction="vertical" />
        <el-button type="danger" plain @click="deleteUser(scope.row)">
          <Delete style="width: 1em; height: 1em" />
        </el-button>
        <el-divider direction="vertical" />
        <el-button type="primary" plain @click="showUpdatePassword(scope.row)">
          修改密码
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
  <el-pagination
    class="pagination"
    :current-page="pageInfo.pageNo"
    :page-size="pageInfo.pageSize"
    :page-sizes="[5, 10, 15]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="pageInfo.totalCount"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />

  <!-- 新增、修改专题窗口 -->
  <el-dialog
    v-model="editFormConfig.show"
    :title="editFormConfig.title"
    @closed="closedEditForm"
    draggable
    width="60%"
  >
    <el-form
      :model="editForm"
      label-position="top"
      :rules="rules"
      ref="editFormRef"
      label-width="110px"
    >
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="头像" prop="avatar">
            <CoverUpload v-model="editForm.avatar"></CoverUpload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="昵称" prop="nickName">
            <el-input :maxLength="30" v-model="editForm.nickName" placeholder="请输入昵称">
            </el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input :maxLength="11" v-model="editForm.phone" placeholder="请输入手机号">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10" v-if="editForm.userId == null">
        <el-col :span="12">
          <el-form-item label="密码" prop="password">
            <el-input v-model="editForm.password" :maxLength="20" type="password" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="再次输入密码" prop="rePassword">
            <el-input v-model="editForm.rePassword" :maxLength="20" type="password" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="默认编辑器" prop="editorType">
            <el-radio-group v-model="editForm.editorType">
              <el-radio :label="0">富文本编辑器</el-radio>
              <el-radio :label="1">MarkDown编辑器</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职业" prop="profession">
            <el-input v-model="editForm.profession" placeholder="请输入职业">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="简介" prop="introduction">
            <EditorMarkdown v-model="editForm.introduction"></EditorMarkdown>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10" justify="center">
        <el-col :span="2">
          <el-form-item>
            <el-button type="success" @click="editFormSubmit">确定</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>

  <!-- 修改密码对话框 -->
  <el-dialog
    v-model="changePasswordVisible"
    title="修改密码"
    width="30%"
    @closed="closedChangePasswordVisible"
    draggable
  >
    <el-form
      :model="passwordFormData"
      :rules="rules"
      ref="passwordFormDataRef"
      label-width="80px"
      label-position="top"
    >
      <el-form-item label="新密码" prop="password">
        <el-input
          placeholder="请输入密码"
          type="password"
          show-password
          v-model="passwordFormData.password"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="重复密码" prop="rePassword">
        <el-input
          placeholder="请再次输入密码"
          type="password"
          show-password
          v-model="passwordFormData.rePassword"
        >
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="changePasswordVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPassword"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, onBeforeMount, nextTick } from "vue";
const { proxy } = getCurrentInstance();

onBeforeMount(() => {
  getDataList();
});

// 数据表格相关
// 搜索数据表单
const searchFormData = reactive({});
// 搜索数据
const getDataList = async () => {
  let params = {
    pageNo: tableData.value.pageNo,
    pageSize: tableData.value.pageSize,
  };
  Object.assign(params, searchFormData);
  let result = await proxy.Request({
    url: "/setting/loadUser",
    params,
  });
  if (!result) {
    return;
  }
  tableData.value = result.data;
  pageInfo.pageNo = result.data.pageNo;
  pageInfo.pageSize = result.data.pageSize;
  pageInfo.totalCount = result.data.totalCount;
};
// 数据
const tableData = ref({});

// 修改状态
const loading = ref(false);
const beforeChange = async (data) => {
  loading.value = true;
  let result = await proxy.Request({
    url: "/setting/updateStatus",
    params: {
      userId: data.userId,
      status: data.status == 0 ? 1 : 0,
    },
  });
  if (!result) {
    loading.value = false;
    return false;
  }
  loading.value = false;
  proxy.$message.success("修改状态成功");
  getDataList();
};

// 分页相关
// 分页数据
const pageInfo = reactive({
  pageNo: 1,
  pageSize: 15,
  totalCount: 0,
});
// 页容量改变
const handleSizeChange = (val) => {
  pageInfo.pageSize = val;
  getDataList();
};
// 页码改变
const handleCurrentChange = (val) => {
  pageInfo.pageNo = val;
  getDataList();
};

// 新增、编辑用户窗口
// 配置
let editFormConfig = reactive({
  show: false,
  title: "新增用户",
});
// 用户表单
const editForm = ref({});
// 表单规则
const editFormRules = {
  categoryName: [{ required: true, message: "请输入分类名称" }],
};
// 打开表单
const openUserVisible = (type, data) => {
  editFormConfig.show = true;
  nextTick(() => {
    proxy.$refs.editFormRef.resetFields();
    if (type == "add") {
      editFormConfig.title = "新增用户";
    } else {
      editFormConfig.title = "修改用户";
      editForm.value = JSON.parse(JSON.stringify(data));
    }
  });
};
// 关闭表单
const closedEditForm = () => {
  proxy.$refs.editFormRef.resetFields();
  editForm.value.userId = undefined;
};
// 提交表单
const editFormSubmit = () => {
  proxy.$refs.editFormRef.validate(async (valid) => {
    if (!valid) {
      return;
    }
    let params = {};
    Object.assign(params, editForm.value);
    delete params.createTime;
    delete params.lastLoginTime;
    let result = await proxy.Request({
      url: "/setting/saveTeamUser",
      params,
    });
    if (!result) {
      proxy.$message.error(`${editFormConfig.title}失败`);
      return;
    }
    proxy.$message.success(`${editFormConfig.title}成功`);
    editFormConfig.show = false;
    getDataList();
  });
};
// 删除用户
const deleteUser = (data) => {
  proxy.$messageBox
    .confirm("确认删除吗？", "删除用户", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(async () => {
      let result = await proxy.Request({
        url: "/setting/delUser",
        params: {
          userId: data.userId,
        },
      });
      if (!result) {
        proxy.$message.error("删除失败");
        return;
      }
      proxy.$message.success("删除成功");
      getDataList();
    })
    .catch(() => {
      proxy.$message.info("取消删除");
      return;
    });
};

// 密码校验
const validateRePass = (rule, value, callback) => {
  if (value !== editForm.value.password) {
    callback(new Error(rule.message));
  } else {
    callback();
  }
};

// 表单校验
const rules = {
  nickName: [{ required: true, message: "昵称不能为空" }],
  editorType: [{ required: true, message: "请选择默认编辑器" }],
  password: [
    { required: true, message: "请输入密码" },
    {
      validator: proxy.Verify.password,
      message: "密码最少8位，只能数字字母和特殊字符",
    },
  ],
  rePassword: [
    { required: true, message: "请再次输入密码" },
    {
      validator: validateRePass,
      message: "两次输入的密码不一致",
    },
  ],
  phone: [
    { required: true, message: "请输入手机号" },
    {
      validator: proxy.Verify.phone,
      trigger: "blur",
      message: "请输入正确的手机号",
    },
  ],
};

// 新密码表单
const passwordFormData = reactive({
  userId: null,
  password: "",
  rePassword: "",
});
// 修改密码对话框显隐控制
let changePasswordVisible = ref(false);
// 显示修改密码对话框
const showUpdatePassword = (data) => {
  changePasswordVisible.value = true;
  nextTick(()=>{
    passwordFormData.userId=data.userId
    proxy.$refs.passwordFormDataRef.resetFields();
  })
};
// 关闭修改密码对话框
const closedChangePasswordVisible = () => {
  proxy.$refs.passwordFormDataRef.resetFields();
  changePasswordVisible.value = false;
};
// 确认修改密码
const submitPassword = () => {
  proxy.$refs.passwordFormDataRef.validate(async (valid) => {
    if (!valid) {
      return;
    }
    let result = await proxy.Request({
      url: "/setting/updatePassword",
      params: {
        userId: passwordFormData.userId,
        password: passwordFormData.password,
      },
    });
    if (!result) {
      proxy.$message.error("修改密码失败");
      return;
    }
    proxy.$message.success("修改密码成功");
    changePasswordVisible.value = false;
  });
};

</script>

<style lang="scss" scoped>
.dataTable {
  margin-top: 20px;
  height: calc(100vh - 320px);

  .blogInfo {
    display: flex;
    flex-direction: column;

    span {
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
  }

  .timeInfo {
    display: flex;
    flex-direction: column;
  }
}
.pagination {
  margin-top: 20px;
}
</style>